import UIRichEditor from '@/components/UI/RichEditor/index.vue'
import { storeToRefs } from 'pinia';
import { ShallowRef } from 'vue'
type sectionEditor = Readonly<ShallowRef<InstanceType<typeof UIRichEditor>>>
let sectionEditor: sectionEditor
const wordCount = ref(0)


export const useEditorAgent = (editor?: sectionEditor) => {
    if (editor) {
        sectionEditor = editor
    }
    const { AIBarChatNowSelectModel } =
        storeToRefs(settingsStore());
    const loading = ref(false)
    const getALlSpanActiveTxt = () => {
        let selectedText = ''
        if (sectionEditor?.value?.editor) {
            const editor = sectionEditor.value.editor
            editor.state.doc.descendants((node) => {
                if (node.marks.find(mark => mark.type.name === 'spanActive')) {
                    selectedText += node.text + '\n'
                }
            })
        }
        return selectedText
    }
    const removeAllSpanActive = () => {
        if (sectionEditor?.value?.editor) {
            const editor = sectionEditor.value.editor
            if (editor) {
                editor
                    .chain()
                    .command(({ tr }) => {
                        const spanMark = editor.schema.marks.span;
                        const spanActiveMark = editor.schema.marks.spanActive;
                        if (!spanMark || !spanActiveMark) return false;
                        tr.setMeta("addToHistory", false);
                        tr.removeMark(0, editor.state.doc.content.size, spanMark);
                        tr.removeMark(0, editor.state.doc.content.size, spanActiveMark);
                        return true;
                    })
                    .run();
            }
        }
    }
    interface sendChatMessageOptions {
        tools?: OpenAITool[]
        stop?: string | null
    }
    const sendChatMessage = (msg: string, opitons: sendChatMessageOptions, callBack?: (isDone: boolean, content?: string, tool_calls?: tool_call[]) => void) => {
        loading.value = true
        return openAiService().ChatCompletion({
            model: AIBarChatNowSelectModel.value?.id,
            messages: [
                {
                    role: 'user',
                    content: msg
                }
            ],
            ...opitons
        }, (isDone: boolean, content?: string, tool_calls?: tool_call[]) => {
            callBack?.(isDone, content, tool_calls)
            if (isDone) {
                loading.value = false
            }
        })
    }
    const createSpanActive = () => {
        if (sectionEditor?.value?.editor) {
            const editor = sectionEditor.value.editor
            const { from, to } = editor.state.selection;
            if (from !== to) {
                editor
                    .chain()
                    .command(({ tr }) => {
                        const spanMark = editor.schema.marks.span;
                        const spanActiveMark = editor.schema.marks.spanActive;
                        if (!spanMark || !spanActiveMark) return false;
                        tr.setMeta("addToHistory", false);
                        tr.removeMark(from, to, spanMark);
                        tr.addMark(from, to, spanActiveMark.create());
                        return true;
                    })
                    .run();
            }
        }
    }
    const replaceMessage = (txt: string) => {
        wordCount.value = txt.split(/\s+/).length;
        if (sectionEditor?.value?.editor) {
            const editor = sectionEditor.value.editor
            editor
                .chain()
                .command(({ tr }) => {
                    const positions: { start: number; end: number }[] = [];
                    editor.state.doc.descendants((node, pos) => {
                        if (node.marks.find(mark => mark.type.name === 'spanActive')) {
                            positions.push({
                                start: pos,
                                end: pos + node.nodeSize
                            });
                        }
                    });
                    if (positions.length === 0) return false;
                    const spanActiveMark = editor.schema.marks.spanActive;
                    const start = positions[0].start;
                    const end = positions[positions.length - 1].end;
                    const lines = txt.split('\n');
                    const fragment = lines
                        .filter(line => line.trim() !== '')
                        .map((line) => {
                            const textNode = editor.schema.text(line.trim());
                            const paragraph = editor.schema.nodes.paragraph.create(null, textNode);
                            return paragraph;
                        });
                    if (fragment.length === 0) return false;
                    tr.replaceWith(start, end, fragment);
                    tr.addMark(start, start + txt.length, spanActiveMark.create());
                    return true;
                })
                .run();
        }
    }
    const copyMessage = (message: string) => {
        const textarea = document.createElement('textarea');
        textarea.value = message;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
    }
    return {
        copyMessage,
        loading,
        sendChatMessage,
        getEditor: () => sectionEditor.value,
        getALlSpanActiveTxt,
        removeAllSpanActive,
        createSpanActive,
        wordCount,
        replaceMessage
    }
}
